﻿using System.Collections.ObjectModel;
using WPFServices.Commands;
using WPFServices.Models.Domain;
using WPFServices.Services.DomainService.Processinfo;

namespace WPFServices.ViewModels.DomainViewModel.Process
{
    public class ProcessViewModel:BaseViewModel
    {
        private readonly ProcessService processService;//工序数据服务
        private ObservableCollection<ProcessesDto> processList;//工序列表
        private ProcessesDto selectedProcess;
        private bool isLoading;

        public ProcessViewModel()
        {
            // 初始化命令，绑定到相应的方法。
            LoadDataCommand = new RelayCommand(async _ => await LoadProcesssAsync());
            SearchCommand = new RelayCommand(async _ => await SearchProcessAsync());

            processService = new ProcessService();
            processList = new ObservableCollection<ProcessesDto>();

            _ = LoadProcesssAsync();
        }


        #region 属性
        public ObservableCollection<ProcessesDto> ProcessesList
        {
            get => processList;
            set => SetProperty(ref processList, value);
        }

        public ProcessesDto SelectedProcess
        {
            get => selectedProcess;
            set=>SetProperty(ref selectedProcess, value);
        }

        public bool IsLoading
        {
            get => isLoading;
            set => SetProperty(ref isLoading, value);
        }

        #endregion

        #region 命令
        public RelayCommand LoadDataCommand { get; }
        public RelayCommand SearchCommand { get; }
        #endregion

        #region 方法
        private async Task LoadProcesssAsync()
        {
            await SearchProcessAsync();
        }

        private async Task SearchProcessAsync()
        {
            try
            {
                IsLoading = true;
                var result = await processService.SearchProcessAsync();
                ProcessesList.Clear();
                if (result != null)
                {
                    foreach (var process in result)
                    {
                        ProcessesList.Add(process);
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                IsLoading = false;
            }
        }
        #endregion

    }
}
